import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/blog_delete")
public class BlogDeleteServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1.先判定用户的登陆状态
        HttpSession session= req.getSession(false);
        if(session==null){
            resp.setStatus(403);
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("当前未登陆，不能删除");
            return;
        }
        User user=(User) session.getAttribute("user");
        if(user==null){
            resp.setStatus(403);
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("当前未登陆，不能删除");
            return;
        }
        //2.获取到blogId
        String blogId=req.getParameter("blogId");
        if(blogId==null){
            resp.setStatus(404);
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("当前删除的blogId有误");
            return;
        }
        //3.查询出这个blogId对应的Blog对象
        BlogDao blogDao=new BlogDao();
        Blog blog=blogDao.selectOne(Integer.parseInt(blogId));
        if(blog==null){
            resp.setStatus(404);
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("当前删除的博客不存在 blogId= "+blogId);
            return;
        }
        //4.判定登陆用户是否是文章作者
        if(blog.getUserId()!=user.getUserId()){
            //blog.getUserId() 文章的作者
            //user.getUserID() 从session中拿到的当前登陆用户
            resp.setStatus(403);
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("当前不能删除别人的博客");
            return;
        }
        //5.真正的执行删除操作
        blogDao.delete(Integer.parseInt(blogId));
        //6.返回302重定向
        resp.sendRedirect("blog_list.html");
    }
}
